#include "xop/RtmpServer.h"
#include "xop/HttpFlvServer.h"
#include "xop/RtmpPublisher.h"
#include "xop/RtmpClient.h"
#include "xop/HttpFlvServer.h"
#include "xop/H264Parser.h"
#include "net/EventLoop.h"

#include <thread>
#include <iostream>
#include <string>

#include "rtmp.h"

bool is_playing = false;
std::thread rtmp_thread;

void StartRTMPServer(int port)
{
    if (is_playing)
    {
        return;
    }
    is_playing = true;

    rtmp_thread = std::thread([=]()
                    {
					   int count = 1;
					   xop::EventLoop event_loop(count);

					   auto rtmp_server = xop::RtmpServer::Create(&event_loop);
					   rtmp_server->SetChunkSize(60000);
					   // rtmp_server->SetGopCache(); /* enable gop cache */
					   rtmp_server->SetEventCallback([](std::string type, std::string stream_path)
													 { printf("[Event] %s, stream path: %s\n\n", type.c_str(), stream_path.c_str()); });
                       if (!rtmp_server->Start("0.0.0.0", port))
                       {
						   printf("RTMP Server listen on %d failed.\n", port);
					   }

					   while(is_playing)
					   {
						   std::this_thread::sleep_for(std::chrono::milliseconds(100));
					   }

					   rtmp_server->Stop(); });
}

void StopRTMPServer()
{
    is_playing = false;
    rtmp_thread.join();
}

